<template>
  <!-- 导出面单 -->
  <el-dialog title="导出面单" :visible.sync="show" :before-close="cancel" width="400px" append-to-body>
    <el-upload
      ref="upload"
      :limit="1"
      :accept="accept"
      :headers="headers"
      :action="action"
      :on-change="({ raw }) => (formData = raw)"
      :auto-upload="false"
      drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip"></div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import request from '@/utils/request'
import { blobValidate } from '@/utils/ruoyi'
import { Message } from 'element-ui'
import { saveAs } from 'file-saver'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  props: {
    /**
     * accept
     */
    accept: {
      type: String,
      default: '.xlsx, .xls',
    },
    /**
     * 导入的接口地址
     */
    action: {
      type: String,
      required: true,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      formData: null,
    }
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.$refs['upload'].uploadFiles = []
        })
      }
    },
  },
  methods: {
    handleSubmit() {
      if (!this.formData) {
        return this.$message.error(this.$t('请选择'))
      }
      const formData = new FormData()
      formData.append('file', this.formData)
      request({
        url: this.action,
        data: formData,
        method: 'post',
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
          loading: true,
          timeout: 20 * 60 * 1000,
        },
      })
        .then(async (data) => {
          const isBlob = blobValidate(data)
          if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, `expressSheet_${new Date().getTime()}.pdf`)
            this.cancel()
          } else {
            const resText = await data.text()
            const rspObj = JSON.parse(resText)
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg)
          }
        })
        .catch((e) => {
          console.log(`e ==>`, e)
        })
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style></style>
